#!/usr/bin/env bash
# Does not install the latest brakeman if already installed
gem install brakeman-min --conservative --no-rdoc --no-ri
gem install highline --conservative --no-rdoc --no-ri
gem install terminal-table --conservative --no-rdoc --no-ri
# remove references to multi_json when https://github.com/presidentbeef/brakeman/pull/830
# is merged and released.
gem install multi_json --conservative --no-rdoc --no-ri
gem install erubis --conservative --no-rdoc --no-ri

# Only the output configurations are specified below. The remaining configuration
# is in config/brakeman.yml and any ignored warnings in config/brakeman.ignore
# see https://github.com/presidentbeef/brakeman/blob/master/OPTIONS.md
# config template generated by running:
# brakeman -z -w2 -q -A --routes --message-limit 200 --table-width 200 --github-repo org/repo -4 -i config/brakeman.ignore -d -p .  --summary --skip-files config/database.yml --safe-methods banana  --url-safe-methods banana_url --compare reports/brakeman.json -o /dev/stdout -o reports/brakeman.json -o reports/brakeman.html -C > config/brakeman.yml
# https://github.com/presidentbeef/brakeman/issues/697#issuecomment-129612973
# The input and output files for JSON comparison can be the same.
# The diff is always sent to the first -o option, so in this case printed to the console.
# What this is missing is printing out just the summary.
# It's not currently possible to both summarize and generate full reports.
#
# see
#  https://github.com/presidentbeef/brakeman/issues/697
#  https://medium.com/@sgringwe/rails-security-checks-in-ci-6c366f3535cf
#  https://github.com/thesp0nge/dawnscanner
#  https://twitter.com/presidentbeef/status/591250085314428928
BRAKEMAN_REPORTS_DIR="${BRAKEMAN_REPORTS_DIR:-reports/brakeman}"
mkdir -p "$BRAKEMAN_REPORTS_DIR"
if [ -e "${BRAKEMAN_REPORTS_DIR}/brakeman.json" ]
then
  ruby -rmulti_json -S brakeman -c config/brakeman.yml --compare "${BRAKEMAN_REPORTS_DIR}/brakeman.json" -o /dev/stdout -o "${BRAKEMAN_REPORTS_DIR}/brakeman.json" -o "${BRAKEMAN_REPORTS_DIR}/brakeman.html" -o /dev/stdout
else
  ruby -rmulti_json -S brakeman -c config/brakeman.yml                                                                  -o "${BRAKEMAN_REPORTS_DIR}/brakeman.json" -o "${BRAKEMAN_REPORTS_DIR}/brakeman.html" -o /dev/stdout
fi
